<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { useI18n } from '@/hooks/web/useI18n'
import { ElTree, ElMessage } from 'element-plus'
import { rolePermissionsApi, rolePermissionsUpdateApi } from '@/api/role'
import { useClipboard } from '@/hooks/web/useClipboard'

const { t } = useI18n()
const { copy, copied } = useClipboard()

const props = defineProps({
  currentRow: {
    type: Object as PropType<any>,
    default: () => undefined
  }
})

const treeRef = ref<typeof ElTree>()

const treeData = ref([])
const defaultChecked = ref([])

const getRolePermissions = async () => {
  const res = await rolePermissionsApi(props.currentRow.id)
  if (res.code === 200) {
    treeData.value = res.data.systemPermissions
    defaultChecked.value = res.data.assignedPermissions || []
  }
}

getRolePermissions()

const onCopy = (text) => {
  copy(text)
}

watchEffect(() => {
  if (copied.value) {
    ElMessage.success(t('toast.copySuccess'))
  }
})

const isDebug = computed(() => import.meta.env.VITE_USER_NODE_ENV === 'development')

const formSchema = ref<FormSchema[]>([
  {
    field: 'permissionList',
    label: t('common.selectText'),
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          const slots = ({ node, data }) => (
            <>
              <span class="custom-tree-node">
                <span>{node.label}</span>
                <span v-show={isDebug.value && data.api} class="ml-5">
                  {data.api}
                </span>
                <span v-show={isDebug.value && data.api} class="ml-3">
                  <a class="text-blue-500" onClick={() => onCopy(data.api)}>
                    {t('common.copy')}
                  </a>
                </span>
              </span>
            </>
          )
          return (
            <>
              <div class="flex w-full">
                <div class="flex-1">
                  <ElTree
                    ref={treeRef}
                    show-checkbox
                    highlight-current
                    node-key="id"
                    default-expand-all
                    data={treeData.value}
                    default-checked-keys={defaultChecked.value}
                    v-slots={slots}
                  />
                </div>
              </div>
            </>
          )
        }
      }
    }
  }
])

const { formRegister, formMethods } = useForm()
const { getFormData, getElFormExpose } = formMethods

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    const permissionList = treeRef.value?.getCheckedKeys(true) || []
    if (permissionList.length === 0) {
      ElMessage.error(t('role.permissionEmptyTip'))
      return
    }
    await rolePermissionsUpdateApi({
      roleId: props.currentRow.id,
      permissionList
    })
    return formData
  }
}

defineExpose({
  submit
})
</script>

<template>
  <Form @register="formRegister" :schema="formSchema" />
</template>
